<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);


date_default_timezone_set('PRC');


use \GatewayWorker\Lib\Gateway;
use \Workerman\Lib\Timer;
use \GatewayWorker\Lib\Db;
//require_once  __DIR__ . '/../../\Applications\Timer\Config\Store.php;
 
 
/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id) {
        // 向当前client_id发送数据 
        Gateway::sendToClient($client_id, "Hello $client_id");
        // 向所有人发送
        Gateway::sendToAll("$client_id login");
    }
    
   /**
    * 当客户端发来消息时触发
    * @param int $client_id 连接id
    * @param mixed $message 具体消息
    */
   public static function onMessage($client_id, $message) {
        // 向所有人发送 
        Gateway::sendToAll("$client_id said $message");
   }
   
   /**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
   public static function onClose($client_id) {
       // 向所有人发送 
       GateWay::sendToAll("$client_id logout");
   }
   
   /**
    * 当本进程启动时触发
    * @param int  
    */
   public static function onWorkerStart($businessworker) {
       // 向所有人发送 
	   //测试本程序执行时间
		//$start_time = microtime(true);
		$time_interval = 1;
		//插入车辆数据临时信息数据库
		$timer = 0;
		
		
		/* $mem = new Memcache;
		//连接memcache服务器
		$mem -> connect("127.0.0.1", 11212); */
		Db::instance('user')->query(" INSERT ims_bus_location_temp(longitude,latitude,imei,quantity_gps,workerman_id,time)SELECT  longitude,latitude,imei,quantity_gps,workerman_id,time FROM ims_bus_locations ; ");
		Db::instance('user')->query(" TRUNCATE  TABLE `ims_bus_location_temp1` ; ");
		Db::instance('user')->query(" INSERT INTO ims_bus_location_temp1(id,data) VALUES (1,''); ");
		Timer::add($time_interval, function()
		{
			 
			//$select_result = Db::instance('user')->query(" select * from `ims_bus_locations` a where not exists (select 1 from `ims_bus_locations` where imei=a.imei and time>a.time); ");
			$select_result = Db::instance('user')->query(" select * from `ims_bus_locations` ; ");
 			$result_lenth = count($select_result);
			$i=0;

			//对一次100个转换数据求模求余
			$loop_mod = floor($result_lenth/100);
			$loop_rem = $result_lenth%100;
			//转换100的整数倍个数据（百度接口单次最多接受100个数据）
			for($loop=0; $loop < $loop_mod; $loop++) {
				for($i=0;$i<100;$i++) {
					$lat = substr($select_result[$loop*100+$i]["latitude"],2);
					$lon = substr($select_result[$loop*100+$i]["longitude"],3);
					$lon_m = $lon / 60;
					$lat_m = $lat / 60;
					$lon_m = substr($lon_m,1);
					$lat_m = substr($lat_m,1);
					$latitude = substr_replace([$loop*100+$i]["latitude"] , $lat_m , 2);
					$longitude = substr_replace([$loop*100+$i]["longitude"] , $lon_m , 3);
					$data = $data . $longitude . "," . $latitude .";";
				}
				$data = rtrim($data , ";");
				$url ="http://api.map.baidu.com/geoconv/v1/?coords=". $data ."&ak=46E056Da83a0e9c2d010770335c9ede9"; 
				$results = file_get_contents($url);
				$result = json_decode($results, true);
				if($result['status'] == 0) {
					for($j=0;$j<100;$j++) {	
						/* $k1[] = '`'.$k.'`';  //将字段作为一个数组；  
						$v1[] = '"'.$v.'"';  //将插入的值作为一个数组； */ 
						$select_result[$loop*100+$j]['longitude'] = $result['result'][$loop]['x'];
						$select_result[$loop*100+$j]['longitude'] = $result['result'][$loop]['y'];
					}
				} else {
					//输出错误的返回信息
					return(print_r ($result));
				}
			}
			

			//转换余下的数据
			for($i=0;$i<$loop_rem;$i++) {
				$lat = substr($select_result[$loop*100+$i]["latitude"],2);
				$lon = substr($select_result[$loop*100+$i]["longitude"],3);
				$lon_m = $lon / 60;
				$lat_m = $lat / 60;
				$lon_m = substr($lon_m,1);
				$lat_m = substr($lat_m,1);
				$latitude = substr_replace($select_result[$i]["latitude"] , $lat_m , 2);
				$longitude = substr_replace($select_result[$i]["longitude"] , $lon_m , 3);
				$data = $data . $longitude . "," . $latitude .";";
				
			}
			$data = rtrim($data , ";");
			$url ="http://api.map.baidu.com/geoconv/v1/?coords=". $data ."&ak=46E056Da83a0e9c2d010770335c9ede9"; 
			
			$results = file_get_contents($url);
			$result = json_decode($results, true);
			var_dump($result);
			
			$mem -> add("test", "ssss", MEMCACHE_COMPRESSED, 0);
			//返回其他错误码的时候，输出返回信息
			if($result['status'] == 0) {
				for($j=0;$j<$loop_rem;$j++) {	
					$select_result[$j]['longitude'] = $result['result'][$j]['x'];
					$select_result[$j]['latitude']  = $result['result'][$j]['y'];
				}
				$insert_data = json_encode($select_result);
				//print_r($insert_data);
				//$insert_result = Db::instance('user')->query(" UPDATE `ims_bus_location_temp1` SET  data  =  '$insert_data'  WHERE id = 1    ");
				//测试服务器性能语句
				$insert_result = Db::instance('user')->query(" INSERT INTO ims_bus_location_temp1 (data) VALUES ('$insert_data');");
			} else {
				//输出错误的返回信息
				return(print_r ($result));
			}
			 //var_dump($mem->get("test"));
			
		 	
			//测试本程序执行时间
			//$end_time = microtime(true);
			//$total=$end_time-$start_time;
			
			
		});		
			
		
   }
   


}
